﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

namespace Middlerware.Sample
{
    // You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
    public class RequestIdInRequestMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestIdInRequestMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext httpContext)
        {
            //request head 加入requestid
            var requestId = Guid.NewGuid().ToString("n");
            httpContext.Request.Headers.Add("REQUESTID", requestId);

            return _next(httpContext);
        }
    }

    // Extension method used to add the middleware to the HTTP request pipeline.
    public static class RequestIdMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestIdInRequestMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestIdInRequestMiddleware>();
        }
    }
}
